//
//  Youjiku.m
//  Tour
//
//  Created by 张张烨 on 16/3/23.
//  Copyright © 2016年 张中烨. All rights reserved.
//

#import "Youjiku.h"

@interface Youjiku ()
@property (nonatomic, strong) FMDatabase *fmdb;

@end

@implementation Youjiku
+ (Youjiku *)shareInstance
{
    static Youjiku *dbManager = nil;
    if (!dbManager) {
        dbManager = [[Youjiku alloc]init];
    }
    return dbManager;
}
// 封装: 执行+判断
// 参数1: 需要执行的SQL语句
// 参数2: 执行之后的打印信息
- (void)executeSQL:(NSString *)sql message:(NSString *)mes
{
    // 执行
    BOOL result = [_fmdb executeUpdate:sql];
    // 判断
    if (result) {
        NSLog(@"%@成功", mes);
    } else {
        NSLog(@"%@失败", mes);
    }
}

/**<  打开数据库 */
- (void)openDb
{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fmdb1.pltis"];
    // 创建数据库对象
    self.fmdb = [[FMDatabase alloc] initWithPath:path];
    //打开数据库
    NSLog(@"%@",path);
    BOOL result = [self.fmdb open];
    if (result) {
        NSLog(@"打开数据库");
    }else{
        NSLog(@"打开数据库失败");
    }
    
    
}

/**<  创建表 */
-(void)creteTable
{
    NSString *createSQL = @"CREATE TABLE IF NOT EXISTS SHUJUKU (number integer  PRIMARY KEY AUTOINCREMENT,mingzi text, tupian text, idddd text)";
    [self executeSQL:createSQL message:@"创建表"];
    
}
/**<  增加表 */
-(void)insertWangzhi:(Youjikulei *)biao
{
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO SHUJUKU(mingzi,tupian,idddd) VALUES('%@','%@','%@')",biao.mingzi,biao.tupian,biao.idddd];
    [self executeSQL:insertSQL message:@"增加"];
    
}
//删除
-(void)deleteNumber:(NSString * )num{
    NSString *deleteSQL = [NSString stringWithFormat:@"DELETE FROM SHUJUKU WHERE mingzi = '%@'",num ];
    [self executeSQL:deleteSQL message:@"删除"];
}

//查询
-(NSMutableArray *)selet{
    //  返回需要返回的数据
    NSMutableArray *arr = [NSMutableArray array];
    //SQL
    NSString *selectSQL = @"SELECT *FROM SHUJUKU";
    
    //执行查询语句
    FMResultSet *resultSet = [_fmdb executeQuery:selectSQL];
    //reslultSet 标示 查询到的数据 同过遍历每一行信息 然后逐行获取数据
    
    while ([resultSet next]) {
        //获取每一列
        //number是第0页
        //获取方式分两种 列名 / 列号获取
        NSString *mingzi = [resultSet stringForColumn:@"mingzi"];
        NSString *tupian = [resultSet stringForColumn:@"tupian"];
        NSString *idddd = [resultSet stringForColumn:@"idddd"];
        //创建对象 保存信息
        Youjikulei *l = [[Youjikulei alloc]init];
        l.mingzi = mingzi;
        l.tupian = tupian;
        l.idddd = idddd;
        //添加到数组
        [arr addObject:l];
    }
    //返回数组
    return arr;
}

@end
